/**
 * 日期格式化工具函数
 */

/**
 * 格式化日期为 YYYY-MM-DD 格式
 */
export function formatDate(date: Date): string {
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  return `${year}-${month}-${day}`
}

/**
 * 格式化时间为 HH:mm 格式
 */
export function formatTime(dateStr: string): string {
  const date = new Date(dateStr)
  const hours = String(date.getHours()).padStart(2, '0')
  const minutes = String(date.getMinutes()).padStart(2, '0')
  return `${hours}:${minutes}`
}

/**
 * 格式化日期时间为 MM-DD HH:mm 格式
 */
export function formatDateTime(dateStr: string): string {
  const date = new Date(dateStr)
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  const hours = String(date.getHours()).padStart(2, '0')
  const minutes = String(date.getMinutes()).padStart(2, '0')
  return `${month}-${day} ${hours}:${minutes}`
}

/**
 * 获取相对时间描述
 */
export function getRelativeTime(dateStr: string): string {
  const now = new Date()
  const date = new Date(dateStr)
  const diff = now.getTime() - date.getTime()

  const minutes = Math.floor(diff / (1000 * 60))
  const hours = Math.floor(diff / (1000 * 60 * 60))
  const days = Math.floor(diff / (1000 * 60 * 60 * 24))

  if (minutes < 1) {
    return '刚刚'
  }
  else if (minutes < 60) {
    return `${minutes}分钟前`
  }
  else if (hours < 24) {
    return `${hours}小时前`
  }
  else if (days < 7) {
    return `${days}天前`
  }
  else {
    return formatDate(date)
  }
}

/**
 * 判断是否为今天
 */
export function isToday(dateStr: string): boolean {
  const today = new Date()
  const date = new Date(dateStr)

  return today.getFullYear() === date.getFullYear()
    && today.getMonth() === date.getMonth()
    && today.getDate() === date.getDate()
}

/**
 * 判断是否为昨天
 */
export function isYesterday(dateStr: string): boolean {
  const yesterday = new Date()
  yesterday.setDate(yesterday.getDate() - 1)
  const date = new Date(dateStr)

  return yesterday.getFullYear() === date.getFullYear()
    && yesterday.getMonth() === date.getMonth()
    && yesterday.getDate() === date.getDate()
}

/**
 * 获取友好的日期描述
 */
export function getFriendlyDate(dateStr: string): string {
  if (isToday(dateStr)) {
    return '今天'
  }
  else if (isYesterday(dateStr)) {
    return '昨天'
  }
  else {
    const date = new Date(dateStr)
    const month = date.getMonth() + 1
    const day = date.getDate()
    return `${month}月${day}日`
  }
}
